package edu.pitt.dbmi.odie.gapp.gwt.server.umls;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.allen_sauer.gwt.log.client.Log;

import edu.pitt.dbmi.odie.gapp.gwt.server.util.rest.ODIE_NcboRestUtils;
import edu.pitt.dbmi.odie.gapp.gwt.server.util.umls.ODIE_UmlsService;
import edu.pitt.dbmi.odie.gapp.gwt.server.util.umls.ODIE_UmlsServiceFetcher;

@SuppressWarnings("serial")
public class ODIE_UmlsServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		String payLoad = ODIE_NcboRestUtils.getEmptyPayload();

		ODIE_UmlsService umlsService = ODIE_UmlsServiceFetcher
				.fetchUmlsService(this);

		if (umlsService != null) {
			String sab = req.getParameter("ontologyId");
			String cui = req.getParameter("clsId");
			String parents = req.getParameter("parents");
			String children = req.getParameter("children");

			StringBuffer sb = new StringBuffer();
			sb.append("ODIE_UmlsServlet: ");
			sb.append("sab = " + sab + ", ");
			sb.append("cui = " + cui + ", ");
			sb.append("parents = " + parents + ", ");
			sb.append("children = " + children);
			Log.debug(sb.toString());

			if (!ODIE_NcboRestUtils.isNull(sab)
					&& !ODIE_NcboRestUtils.isNull(cui)
					&& !ODIE_NcboRestUtils.isNull(parents)
					&& ODIE_NcboRestUtils.isNull(children)) {
				payLoad = umlsService.getXmlForCuiParents(sab, cui);
			} else if (!ODIE_NcboRestUtils.isNull(sab)
					&& !ODIE_NcboRestUtils.isNull(cui)
					&& ODIE_NcboRestUtils.isNull(parents)
					&& !ODIE_NcboRestUtils.isNull(children)) {
				payLoad = umlsService.getXmlForCuiChildren(sab, cui);
			} else if (!ODIE_NcboRestUtils.isNull(sab)
					&& !ODIE_NcboRestUtils.isNull(cui)
					&& ODIE_NcboRestUtils.isNull(parents)
					&& ODIE_NcboRestUtils.isNull(children)) {
				payLoad = umlsService.getXmlForCui(sab, cui);
			} else if (!ODIE_NcboRestUtils.isNull(sab)
					&& ODIE_NcboRestUtils.isNull(cui)
					&& ODIE_NcboRestUtils.isNull(parents)
					&& ODIE_NcboRestUtils.isNull(children)) {
				payLoad = umlsService.getXmlForSab(sab);
			} else if (ODIE_NcboRestUtils.isNull(sab)
					&& ODIE_NcboRestUtils.isNull(cui)
					&& ODIE_NcboRestUtils.isNull(parents)
					&& ODIE_NcboRestUtils.isNull(children)) {
				payLoad = umlsService.getXmlForSab();
			}
		}

		resp.getOutputStream().write(payLoad.getBytes());
		resp.getOutputStream().close();

	}

}
